//
//  NSDate+Extension.swift
//  BaoKeSwift
//
//  Created by geek-duan on 2017/10/11.
//  Copyright © 2017年 geek-duan. All rights reserved.
//

import Foundation

extension Date {
    
    // MARK: - 是否为今年
    func isThisYear() -> Bool {
        let calender = Calendar.current
        let currentYear = calender.component(.year, from: Date())
        let assignYear = calender.component(.year, from: self)
        return assignYear == currentYear
    }
    
    // MARK: - 是否为今天
    func isToday() -> Bool {
        let fmt = DateFormatter()
        fmt.dateFormat = "yyyy-MM-dd"
        let currentDay = fmt.string(from: Date())
        let assignDay = fmt.string(from: self)
        return currentDay == assignDay
    }
    
    // MARK: - 返回今天字符串 
    func TodayStr() -> String {
        let fmt = DateFormatter()
        fmt.dateFormat = "yyyy-MM-dd"
        let isTodayStr = fmt.string(from: Date())
        return isTodayStr
    }
    
    // MARK: - 是否为昨天
    func isYesterday() -> Bool {
        let fmt = DateFormatter()
        fmt.dateFormat = "yyyy-MM-dd"
        guard  let currentDate = fmt.date(from: fmt.string(from: Date())),
        let assignDate = fmt.date(from: fmt.string(from: self)) else {
            return false
        }
        let calendar = Calendar.current
        let cmps = calendar.dateComponents([.day, .month, .year], from: assignDate, to: currentDate)
        return cmps.year == 0 && cmps.month == 0 && cmps.day == 1
    }
    
    // MARK: - 返回组件Components
    func cmpsFrom(date: Date) -> DateComponents {
        let calendar = Calendar.current
        let components: Set<Calendar.Component> = [.year, .month, .day, .hour, .minute, .second]
        return calendar.dateComponents(components, from: date, to: self)
    }
    
    // MARK: - 通过时间戳返回时间字符串
    func dateStrFromCstampTime(timeStamp: Int) -> String {
        let fmt = DateFormatter()
        let assignDate = Date.init(timeIntervalSince1970: TimeInterval(timeStamp / 1000))
        if assignDate.isThisYear() { //今年
            if assignDate.isToday() {
                let comps = Date().cmpsFrom(date: assignDate)
                
                if let hour = comps.hour,
                let minute = comps.minute {
                    if hour >= 1 {
                        return String(format: "%zd小时前", hour)
                    } else if minute >= 1 {
                        return String(format: "%zd分钟前", minute)
                    } else {
                        return "刚刚"
                    }
                }
            } else if assignDate.isYesterday() {
                fmt.dateFormat = "昨天 HH:mm"
                return fmt.string(from: assignDate)
            } else {
                fmt.dateFormat = "MM-dd HH:mm"
                return fmt.string(from: assignDate)
            }
        } else { //非今年
            fmt.dateFormat = "yy-MM-dd"
            return fmt.string(from: assignDate)
        }
        return ""
    }
}





